package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.common.ZhongConfig;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.exception.ZyantExceptionUtils;
import com.yiboshi.rehrs.param.TraceInfo;
import com.yiboshi.rehrs.param.TraceInfoItem;
import com.yiboshi.rehrs.param.ZhongReq;
import com.yiboshi.rehrs.param.ZhongRes;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author jack 2025/3/20
 */
@Service("HelperZhong_2")
@Slf4j
public class HelperDaxiang extends HelperZhong {

    @Autowired
    ZhongConfigHelper configHelper;

    @Autowired
    RedisHelper redisHelper;




    int mode = 2;

    public int getMode() {
        return mode;
    }

    public ZhongConfig getZhongConfig() {
        return configHelper.getConfig(mode);
    }

    public ZhongRes<TraceInfo> queryTraceRes(String waybillNo){
        try{
            TraceInfo traceInfo = queryTrace(waybillNo);
            if(traceInfo!=null){
               return ZhongRes.ok(traceInfo);
            }
        }catch (ZhongException e){
            return ZhongRes.fail(e.getMessage());
        }catch ( Exception e){
            log.error("轨迹查询异常，{}",e.getMessage());
            return ZhongRes.fail("系统错误，请联系客服");
        }
        return ZhongRes.fail("无轨迹信息");

    }

    //
    private TraceInfo queryTrace(String waybillNo){
        ZhongUser zhongUser = getModeVipUser(true);
        String token = zhongUser.getToken();
        ZhongReq zhongReq = new ZhongReq();
        ZhongConfig zhongConfig = getZhongConfig();
        zhongReq.setAccount(zhongUser.getAccount());
        String api = "token=%s&type=searchMailPost_new&code=%s&pda_user_token=&imei=869296041015581&dev=&time=%d";
        zhongReq.setOriginData(String.format(api,token,waybillNo,System.currentTimeMillis()));
        encode(zhongConfig,zhongReq);
        JSONObject data = send(zhongReq, "vip");
        String string = data.getString("code");
        ZyantExceptionUtils.e(!Objects.equals(string, "200"), data.getString("msg"));

        JSONArray jsonArray = data.getJSONArray("data");
        if (CollUtil.isEmpty(jsonArray)){
            return null;
        }
        TraceInfo traceInfo = new TraceInfo();
        List<TraceInfoItem> traceInfoItemList = new ArrayList<>();
        jsonArray.forEach(o -> {
            JSONObject item = (JSONObject)o;
            String opName = item.getString("opName");
            if(opName.contains("获取基本信息")){
                traceInfo.setReceiverAddress(item.getString("receiverAddress"));
                traceInfo.setReceiverLinker(item.getString("receiverLinker"));
                return;
            }
            String opDesc = item.getString("opDesc");
            if(opName.contains("收寄计费信息")){
                traceInfo.setPostagePaid(item.getString("opDesc"));
            }
            TraceInfoItem traceInfoItem = new TraceInfoItem();
            traceInfoItem.setOpTime(item.getString("opTime"));
            if(opName==null||opName.contains(opDesc)||opDesc.matches("[a-zA-Z0-9]+")){
                opDesc = "";
            }
            traceInfoItem.setOpDesc(opDesc);
            traceInfoItem.setOpOrgName(item.getString("opOrgName"));
            traceInfoItem.setOperatorName(item.getString("operatorName"));
            traceInfoItem.setOpName(opName);
            traceInfoItemList.add(traceInfoItem);
        });
        traceInfo.setTraceInfoItemList(traceInfoItemList);
        return traceInfo;
    }

    public void deleteVipTokenCache(){

        String key = vipTokenKey();
        CacheUtils.delByCache10Min( key,ZhongUser.class);
        redisHelper.delCache( key);
        CacheUtils.delByCache10Min( key,ZhongUser.class);
        redisHelper.deleteHelper("2");
    }

    @Override
    protected JSONObject decode(String dataStr) {
        ZhongConfig zhongConfig = getZhongConfig();
        return decode(zhongConfig,dataStr);
    }

    public ZhongUser getModeVipUser(boolean fromCache){
        String key = vipTokenKey();
        ZhongUser zhongUser = fromCache?CacheUtils.getByCache10Min(key, ZhongUser.class):null;
        if(zhongUser==null){
            zhongUser = !fromCache?null:redisHelper.loadByCache(key,ZhongUser.class);
            if(zhongUser!=null){
                CacheUtils.putByCache10Min(key,zhongUser);
            }
        }
        if(zhongUser==null){
            zhongUser = logonToken();
        }
        if(zhongUser==null){
            return null;
        }
        CacheUtils.putByCache10Min(key,zhongUser);
        redisHelper.save(key,zhongUser,18+AperStringUtils.randomNum(10),TimeUnit.MINUTES);
        //String vipToken = zhongUser.getToken();
        return zhongUser;
    }

    @Override
    public Map<String, String> vipHeader(ZhongUser zhongSessionUser, ZhongReq zhongReq) {
        ZhongUser zhongUser = getModeVipUser(true);
        String vipToken = zhongUser.getToken();
        String type = zhongReq.getType();
        ZhongConfig zhongConfig = getZhongConfig();

        String typeNew = zhongConfig.getOtherMap().get(type);
        type = StrUtils.isNotBlank(typeNew)?typeNew:type;
        String cpsValueKey = "cps-value:dx:"+type;
        int time = getTimeOut(type);
        String mapStr = time<=0?"":stringRedisTemplate.opsForValue().get(cpsValueKey);
        Map<String, String> vipHeader = null;
        String pda_user_token = zhongSessionUser.getToken();
        if(StrUtil.isNotBlank(mapStr)){
            log.info("daxiang redis cache cps,type:{}",type);
            vipHeader = JacksonUtils.toMap(mapStr,String.class,String.class);
        }else{
            String data = "token=%s&pda_user_token=%s&type=%s&imei=867382035888381&dev=&time=%d";
            String format = String.format(data, vipToken, MD5.encode(vipToken),type, System.currentTimeMillis());
            if(type.contains("signIn")){
                format = format+"&longitude="+zhongReq.getLongitude()+"&latitude="+zhongReq.getLatitude();
            }
            //log.info("dx get cps type:{} format:{}",type,format);
            zhongReq.setOriginData(format);
            encode(zhongConfig,zhongReq);
            JSONObject vip = send(zhongReq, "vip");
            vipHeader = HelperXiaofei.toHeader(vip);
            if(CollUtil.isNotEmpty(vipHeader)){
                //vipHeader.remove("requestUnifyCode");
                if(time>0){
                    stringRedisTemplate.opsForValue().set(cpsValueKey,JacksonUtils.toString(vipHeader),time,TimeUnit.SECONDS);
                }

            }
        }

        //固定imei：867382035888381
        //运单列表：origin-req=token=16b2cd2288119fe91b596ca77277624d&pda_user_token=a7ccc210a1c047cb8a96cf24985aa04e&type=changenav&imei=867382035888381&dev=&time=1744185583617
        //查询运单：origin-req=token=16b2cd2288119fe91b596ca77277624d&pda_user_token=a7ccc210a1c047cb8a96cf24985aa04e&type=querywaybill&imei=867382035888381&dev=&time=1744185781550
        //origin-req=token=16b2cd2288119fe91b596ca77277624d&pda_user_token=a7ccc210a1c047cb8a96cf24985aa04e&type=newCallAndFile&imei=867382035888381&dev=&time=1744185782220
        //



        //重新签名
        long time_new = System.currentTimeMillis()+1000;
        vipHeader.put("jdpt_req_time", time_new + "");
        String account = zhongSessionUser.getAccount();
        vipHeader.put("person_no",account);
        vipHeader.put("pda_user_token",pda_user_token);
        vipHeader.put("jdpt_sign", SHA256Util.Jdpt_sign(time_new + "", pda_user_token,account ));
        String padId = zhongSessionUser.getImei();
        if(StrUtils.isBlank(padId)){
            padId = zhongSessionUser.getPadId();
        }
       if(StrUtils.isNotBlank(padId)){
            vipHeader.put("pda_id",padId);
        }else{
            vipHeader.put("android_id", zhongSessionUser.getAndroidId());
        }
        if(Objects.equals(type,"newCallAndFile")){
            vipHeader.put("user-agent","okhttp/3.10.0");
            vipHeader.put("content-type","application/x-www-form-urlencoded; charset=utf-8");
        }
        //log.info("dx type:{} headers:{} ",type,JacksonUtils.toString(vipHeader));
        return vipHeader;
    }




    static Cache<String, Object> cache = CacheUtils.builder(3600);



    //origin-req=account=21530115001085&password=fakepasswd&udid=21530115001085&type=loginbyusrface&imei=351564710852443&dev=&time=1744181017591




    //获取vip用户的token
    public ZhongUser logonToken() {
        try{
            ZhongConfig zhongConfig = getZhongConfig();
            String account = VarConstant.DX_VIP_ACCOUNT;
            //origin-req=account=2153011500199&password=fakepasswd&udid=2153011500199&type=authcode&imei=&dev=&time=1744183275239
            String loginStr = "account=%s&password=fakepasswd&udid=%s&type=authcode&imei=&dev=&time=%d";
            String format = String.format(loginStr, account, account, System.currentTimeMillis());
            ZhongReq zhongReq = new ZhongReq();
            zhongReq.setOriginData(format);
            encode(zhongConfig,zhongReq);
            JSONObject logon = send(zhongReq, "logon");
            JSONObject u_info = logon.getJSONObject("u_info");
            String vipExpDate = u_info.getString("vipExpDate");
            LocalDateTime localDateTime = DateUtils.strToLocalDateTime(vipExpDate);
            if(localDateTime.isAfter(LocalDateTime.now().plusDays(1))){

            }else{
                log.error(account+"，大象账号快过期了");
            }
            ZhongUser zhongUser = new ZhongUser();
            zhongUser.setToken(u_info.getString("token"));
            zhongUser.setAccount(account);
            zhongUser.setImei(u_info.getString("imei"));
            zhongUser.setVipExpDate(localDateTime);
            //Map<String, String> logonHeader = HelperXiaofei.toHeader(logon);
            return zhongUser;
        }catch (Exception e){
            log.error("daxiang vip  登录异常",e);
            return null;
        }

    }


    public Map<String, String> logonHeader(ZhongReq zhongReq) {
        //发短信  origin-req=account=2153011500199&password=fakepasswd&udid=2153011500199&type=authcode&imei=867382035888381&dev=&time=1744184171929
        //短信登录origin-req=account=2153011500166&password=fakepasswd&udid=2153011500166&type=loginbyusrsms&imei=867382035888381&dev=&time=1744184143926
        //注意这里短信登录用返回header中pda_id: 351564710852443

        //867382035888381
        //图片登录origin-req=account=2153011500199&password=fakepasswd&udid=2153011500199&type=loginbyusrface&imei=867382035888381&dev=&time=1744184233478
        //进去后使用返回header的pda_id
        ZhongConfig zhongConfig = getZhongConfig();
        String type = zhongReq.getType();
        String typeNew = zhongConfig.getOtherMap().get(type);
        type = StrUtils.isNotBlank(typeNew)?typeNew:type;
        String loginStr = "account=%s&password=fakepasswd&udid=%s&type=%s&imei=%s&dev=&time=%d";
        String imei = "869296041015581";//zhongReq.getImei();//
        String format = String.format(loginStr, zhongReq.getAccount(), zhongReq.getAccount(),type,imei, System.currentTimeMillis());
        zhongReq.setOriginData(format);
        encode(zhongConfig,zhongReq);
        JSONObject logon = send(zhongReq, "logon");
        log.info("logon:{}",JSONObject.toJSONString(logon));
        Map<String, String> logonHeader = HelperXiaofei.toHeader(logon);
        //重新签名
        long time_new = System.currentTimeMillis()+1000;
        logonHeader.put("jdpt_req_time", time_new + "");
        logonHeader.put("jdpt_sign", SHA256Util.Jdpt_sign(time_new + "", "", zhongReq.getAccount()));
        logonHeader.put("pda_id",zhongReq.getImei());
        return logonHeader;
    }





    @Override
    public Map<String, String> channelHeader(String uri, ZhongUser zhongUser) {
        String type = "";
        ZhongReq zhongReq = new ZhongReq();
        zhongReq.setAccount(zhongUser.getAccount());
        //zhongReq.setImei(zhongUser.getImei());
        zhongReq.setImei("869296041015581");//大象默认
        zhongReq.setTime(System.currentTimeMillis()+"");
        if(uri.contains("loginbyusrface")){
            zhongReq.setType("loginbyusrface");
            return this.logonHeader(zhongReq);
        }else  if(uri.contains("findpdasignwaybillinfonew")){
            type = "changenav";
        }else {
            type = uri.substring(uri.lastIndexOf("/") + 1);
        }
        zhongReq.setType(type);
        return this.vipHeader(zhongUser,zhongReq);
    }




    public static void encode( ZhongConfig zhongConfig,ZhongReq zhongReq) {
        String originData = zhongReq.getOriginData();
       // ZhongConfig zhongConfig = getZhongConfig();
        try {
            String encrypt = MyAESUtil.encrypt(originData, zhongConfig.getAesKeyBytes(), zhongConfig.getAesIvStr());
            String sign = MyAESUtil.sign(originData, zhongConfig.getSignStr());
            zhongReq.setData(encrypt);
            zhongReq.setSign(sign);
            zhongReq.setCoded(1);
        } catch (Exception e) {
            log.error("", e);
        }

    }

    public JSONObject decode( ZhongConfig zhongConfig,String dataStr) {

        String decryptAES = MyAESUtil.decryptAES(dataStr,
                getZhongConfig().getAesKeyStr().getBytes(), zhongConfig.getAesIvStr());
        //log.info("decryptAES:{}", decryptAES);
        JSONObject data = null;
        if (decryptAES.startsWith("{")) {
            data = JSONObject.parseObject(decryptAES);
        } else {
            data = new JSONObject();
            data.put("data", data);
        }
        return data;
    }


    public static void main(String[] args) {
        String encrypt = MyAESUtil.encrypt("123123", "41212a6e7ae3f081106ab92fd616c3b5".getBytes(), "b848d08061100668");
        System.out.println(encrypt);
    }

}
